//
//  TwitterInvoker.m
//  protesteya
//
//  Created by Sebastian Bene on 9/23/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "TwitterInvoker.h"
#import "DataAccess.h"
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#import <Foundation/Foundation.h>

@interface TwitterInvoker ()

@property (nonatomic,strong) ACAccountStore *accountStore;
@property (nonatomic,strong) DataAccess *dataAccess;

@end

@implementation TwitterInvoker

@synthesize tweeterInvokerDelegate;

#define RESULTS_PERPAGE @"100"

- (ACAccountStore *)accountStore
{
    if (_accountStore == nil)
    {
        _accountStore = [[ACAccountStore alloc] init];
    }
    return _accountStore;
}

-(DataAccess *)dataAccess
{
    if(_dataAccess == nil)
        _dataAccess = [[DataAccess alloc] init];
    
    return _dataAccess;
}


-(void) SendTweet:(SendTweetRequest *)request
{   
    NSMutableDictionary * parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        [NSString stringWithFormat:@"%@ %@", request.text, HASHTAG], @"status",
                                        request.latitude, @"lat",
                                        request.longitude, @"long",
                                        @"true", @"display_coordinates",
                                        nil];
    
    if (request.inReplyToStatusId){
        [parameters setObject:request.inReplyToStatusId forKey:@"in_reply_to_status_id"];
    }
    
    if(request.image)
    {
        [self PostToTwitter:parameters withUrl:@"http://api.twitter.com/1.1/statuses/update_with_media.json" withRequestType:SLRequestMethodPOST withImage:request.image];
    }
    else
    {
        [self PostToTwitter:parameters withUrl:@"http://api.twitter.com/1.1/statuses/update.json" withRequestType:SLRequestMethodPOST];
    }
}


-(void) GetTweet:(GetTweetRequest *)request
{
    NSDictionary *parameters = @{@"id": request.tweetId, @"include_entities": @"true"};
    
    [self PostToTwitter:parameters withUrl:@"https://api.twitter.com/1.1/statuses/show.json" withRequestType:SLRequestMethodGET];
}

-(void) GetTweetsList
{
    NSString *encodedQuery = [HASHTAG stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *parameters = @{@"count" : RESULTS_PERPAGE,
                                 @"q" : encodedQuery};
    
    [self PostToTwitter:parameters withUrl:@"https://api.twitter.com/1.1/search/tweets.json" withRequestType:SLRequestMethodGET];
}

-(void) GetTweetComments:(GetTweetCommentsRequest *) request
{
    NSString *encodedQuery = [HASHTAG stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *parameters = @{@"count" : RESULTS_PERPAGE,
                                 @"q" : encodedQuery};

    [self PostToTwitter:parameters withUrl:@"https://api.twitter.com/1.1/search/tweets.json" withRequestType:SLRequestMethodGET];
}

-(void) GetTweetsListByLocation:(GetTweetsListByLocationRequest *)request
{
    NSString *encodedQuery = [HASHTAG stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *parameters = @{@"count" : RESULTS_PERPAGE,
                                 @"q" : encodedQuery,
                                 @"geocode" : [NSString stringWithFormat:@"%@,%@,%@km", request.latitude, request.longitude, GEOCODE_RADIUS ]};
    
    [self PostToTwitter:parameters withUrl:@"https://api.twitter.com/1.1/search/tweets.json" withRequestType:SLRequestMethodGET];
}

-(void) Retweet:(RetweetRequest *)request
{
    NSString *postUrl = [NSString stringWithFormat:@"https://api.twitter.com/1.1/statuses/retweet/%@.json", request.tweetId];
    [self PostToTwitter:nil withUrl:postUrl withRequestType:SLRequestMethodPOST];
    
    [self.dataAccess SetTweetRetweeted:request.tweetId retweeted:YES];
}

-(void) AddToFavorites:(FavoriteRequest *)request
{
    NSDictionary *parameters = @{@"id": [NSString stringWithFormat:@"%@", request.tweetId]};
    
    [self PostToTwitter:parameters withUrl:@"https://api.twitter.com/1.1/favorites/create.json" withRequestType:SLRequestMethodPOST];
    
    [self.dataAccess SetTweetFavorite:request.tweetId favorite:YES];
}

-(void) RemoveFromFavorites:(FavoriteRequest *)request;
{
    NSDictionary *parameters = @{@"id": [NSString stringWithFormat:@"%@", request.tweetId]};
    
    [self PostToTwitter:parameters withUrl:@"https://api.twitter.com/1.1/favorites/destroy.json" withRequestType:SLRequestMethodPOST];
    
    [self.dataAccess SetTweetFavorite:request.tweetId favorite:NO];
}

-(void) PostToTwitter:(NSDictionary *)params withUrl:(NSString *)requestUrl withRequestType:(SLRequestMethod) requestType
{
    [self PostToTwitter:params withUrl:requestUrl withRequestType:requestType withImage:nil];
}

-(void) PostToTwitter:(NSDictionary *)params withUrl:(NSString *)requestUrl withRequestType:(SLRequestMethod) requestType withImage:(UIImage *)image;
{
    ACAccountType *accountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    
    [self.accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
     {
         __block NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
         
         if (granted)
         {
             NSArray *arrayOfAccounts = [self.accountStore
                                         accountsWithAccountType:accountType];
             
             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];
                 
                 NSURL *requestURL = [NSURL URLWithString:requestUrl];
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:requestType
                                           URL:requestURL parameters:params];
                 
                 postRequest.account = twitterAccount;
                 
                 if(image)
                 {
                     NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
                     [postRequest addMultipartData:imageData
                                          withName:@"media[]"
                                              type:@"image/jpeg"
                                          filename:@"image.jpg"];
                 }
                 
                 [postRequest performRequestWithHandler:^(NSData *responseData,
                                                          NSHTTPURLResponse *urlResponse, NSError *error)
                  { 
                      if(error)
                      {
                          [result setObject:[error localizedDescription] forKey:@"errors"];
                      }
                      else
                      {
                          result = [NSJSONSerialization JSONObjectWithData:responseData
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:NULL];
                      }
                      
                      if([tweeterInvokerDelegate respondsToSelector:@selector(getResponse:)])
                      {
                          [tweeterInvokerDelegate getResponse:result];
                      }
                  }];
             }
         }
         else
         {
             [result setObject:[error localizedDescription] forKey:@"errors"];
             
             if([tweeterInvokerDelegate respondsToSelector:@selector(getResponse:)])
             {
                 [tweeterInvokerDelegate getResponse:result];
             }

         }
     }];
}

@end
